/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-23
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-16
 * @Description: 静态服务类，权限认证，初始化用户信息
 */
import 'package:chat_client/services/contact_service.dart';
import 'package:chat_client/services/socket/conversation_service.dart';
import 'package:chat_client/services/user_service.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:chat_client/utils/image-picker/image_picker_helper.dart'; // 引入封装的图片选择工具类
import 'package:chat_client/services/api_service.dart';
import 'package:chat_client/repositories/auth_repository.dart';

class LoginService {
  // 单例模式
  LoginService._internal();
  static final LoginService _instance = LoginService._internal();
  static LoginService get instance => _instance;

  // api 请求服务
  final ApiService apiService = ApiService.instance;
  final AuthRepository authRepository = AuthRepository.instance;
  final UserService userService = UserService.instance;
  final ContactService contactService = ContactService.instance;
  final ConversationService conversationService = ConversationService.instance;

  /// 用户注册
  Future<void> register({
    XFile? imageFile,
    String? nickname,
    required String password,
    required String phoneNumber,
    required String captchaCode,
    required String captchaUid,
  }) async {
    MultipartFile? avatarFile;

    if (imageFile != null) {
      avatarFile = await ImagePickerHelper.convertXFileToMultipart(imageFile);
    }
    final formData = FormData.fromMap({
      'nickname': nickname,
      'password': password,
      'phoneNumber': phoneNumber,
      'captchaCode': captchaCode,
      'captchaUid': captchaUid,
      if (avatarFile != null) 'avatar': avatarFile,
    });
    final registerResponse =
        await apiService.postFormData('/auth/register', formData);
    final username = registerResponse['data']; //提取响应中的用户名

    // 注册成功直接登录
    await login(username, password);
  }

  /// 账号密码登录
  Future<void> login(String username, String password) async {
    final response = await apiService.post('/auth/login', {
      'username': username,
      'password': password,
    });

    // 储存双token
    await authRepository.setToken(
      accessToken: response['data']['access_token'],
      expired: response['data']['expired'],
      refreshToken: response['data']['refresh_token'],
    );
  }

  /// 检查是否存在token
  Future<bool> isLogin() async {
    final token = authRepository.accessToken;
    return !(token == null || token.isEmpty);
  }
}
